package com.lin.manager.file.oss;

import com.lin.manager.common.ex.BizException;
import com.lin.manager.file.entity.FileConfigEntity;
import com.lin.manager.file.model.vo.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @作者: 林江
 * @创建时间: 2024/3/22
 * @功能: 本地上传接口
 */
@Slf4j
public class LocalOssServiceImpl extends AbstractOssService {
    private final static String NAME = "local";

    public LocalOssServiceImpl() {
        super(NAME);
    }

    @Override
    public void doUpload(MultipartFile file, FileConfigEntity fileConfig, Map<String, Object> resp) throws Exception {
        if (isSupport(fileConfig.getPlatform())) {
            log.info("本地文件上传。。。。。。。。。。。。");
            // 生成随机名称
            String fileName = file.getOriginalFilename();
            String suffix = FilenameUtils.getExtension(fileName);
            String newFilename = UUID.randomUUID().toString() + "." + suffix;
            // 会按照当天的时间戳进行来管理文件
            String path = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
            if (StringUtils.isNotBlank(fileConfig.getBucket())) {
                String pp = (fileConfig.getBucket() + "/" + path).replace("//", "/");
                // 上传文件
                File ff = new File(pp + newFilename);

                FileUtils.copyInputStreamToFile(file.getInputStream(), ff);

                // 封装数据
                resp.put(fileConfig.getCode(), createFileVo(ff.getAbsolutePath(), path + newFilename, fileName));
            } else {
                throw new BizException("未知路径。。。。。。。。");
            }
        }
    }

    @Override
    public void doDownload(HttpServletResponse response, FileVo vo, FileConfigEntity fileConfig) throws Exception {
        String newfile = (fileConfig.getBucket() + "/" + vo.getPath()).replace("//", "/");
        log.info("本地文件下载。。。。。。。。。。。。{}", newfile);
        File file = new File(newfile); // 如：win -> D:/xx/xx.png,linux -> /xx/xx.png
        if (file.exists()) {
            byte[] bytes = FileUtils.readFileToByteArray(file);
            write(response, vo.getName(), bytes);
        } else {
            throw new BizException("文件不存在");
        }
    }
}
